<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member\plugin;

use app\common\model\MemberPluginOrder;
use app\manage\model\Member;
use buwang\base\MemberBaseController;
use buwang\service\PluginService;
use think\facade\View;

/**
 * 插件类
 * Class Plugin
 * @package app\manage\controller\member\plugin
 */
class Plugin extends MemberBaseController
{
    public function initialize()
    {
        parent::initialize();
        $this->layout && $this->app->view->engine()->layout($this->layout);
        $this->model = new \app\common\model\Plugin();
    }

    public function index()
    {
        //已启用插件列表
        $list = $this->model->where(['status' => 1])->where("type", 'LIKE', 'member_%')->order('id asc')->select();

        View::assign(compact('list'));
        return view();
    }

    public function detail($id = 0)
    {
        $detail = $this->model->where('id', $id)->where(['status' => 1])->find();
        if (!$detail) return $this->error_jump('插件不存在或未启用');

        //是否已购买
        $has_buy = MemberPluginOrder::where('member_id', $this->user->top_id)->where('plugin_id', $id)->find() ? true : false;

        View::assign(compact('detail', 'has_buy'));
        return view();
    }

    public function buy()
    {
        if (request()->isPost()) {
            if ($this->user->parent_id !== 0) return $this->error('无购买权限');

            $post = $this->request->post();
            $post = reform_keys($post);
            $rule = [];
            $this->validate($post, $rule);

            $detail = $this->model->where('id', $post['id'])->where(['status' => 1])->find();
            if (!$detail) return $this->error('插件不存在或未启用');

            //NOTE 验证支付密码
            if (!Member::checkPassword($post['paypwd'], $this->user['safe_password'])) return $this->error('支付密码错误');

            $this->model->startTrans();
            try {
                PluginService::buy($this->uid, $detail);

                $this->model->commit();
            } catch (\Exception $e) {
                $this->model->rollback();
                return $this->error($e->getMessage());
            }

            return $this->success('购买成功');
        }
    }
}